﻿<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>修改客户</title>
    <script src="~/lib/vue/vue.global.min.js"></script>
    <script src="~/lib/element-plus/index.full.js"></script>
    <link href="~/lib/element-plus/index.min.css" rel="stylesheet" />
    <link href="~/lib/element-plus/index.css" rel="stylesheet" />
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

    <style>
        .container {
            width: 95%;
            margin: 20px auto;
        }

        .form-group {
            margin-bottom: 20px;
            border: 1px solid #ebeef5;
            border-radius: 4px;
            padding: 20px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }

        .form-item {
            margin-bottom: 16px;
        }

        .note-input {
            height: 100px;
        }

        .upload-area {
            margin-top: 20px;
        }

        .tip {
            margin-top: 8px;
            color: #666;
            font-size: 12px;
        }
    </style>
</head>

<body>
    <div class="container">
        <!-- 基础信息 -->
        <div class="form-group">
            <h3>基础信息</h3>
            <el-form ref="basicForm" :model="form" label-width="120px">
                <!-- 第一行：客户编码（只读）、客户名称（必填） -->
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="客户编码" class="form-item">
                            <el-input v-model="form.customer_code" placeholder="自动获取系统编号" readonly></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="客户名称" required class="form-item">
                            <el-input v-model="form.customer_name" placeholder="请输入客户名称"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第二行：所属行业、客户来源（下拉选单，绑定ID，显示中文标签） -->
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="所属行业" required class="form-item">
                            <el-select v-model="form.job_type" placeholder="请选择">
                                <el-option v-for="item in industryOptions" :key="item.dictValue"
                                           :label="item.dictLabel" :value="item.dictValue"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="客户来源" required class="form-item">
                            <el-select v-model="form.sources_of_customers" placeholder="请选择">
                                <el-option v-for="item in customersourceOptions" :key="item.dictValue"
                                           :label="item.dictLabel" :value="item.dictValue"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第三行：联系人、联系电话 -->
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="联系人" class="form-item">
                            <el-input v-model="form.contact_person" placeholder="请输入联系人"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系电话" class="form-item">
                            <el-input v-model="form.contact_phone_number" placeholder="请输入联系电话"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第四行：电子邮箱、销售部门 -->
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="电子邮箱" class="form-item">
                            <el-input v-model="form.email_address" placeholder="请输入电子邮箱"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <!-- 销售部门：树形选择组件 -->
                        <el-form-item label="销售部门" required class="form-item">
                            <div style="display: flex; align-items: center;">
                                <el-input v-model="form.sales_dept_name"
                                          placeholder="请选择部门"
                                          readonly
                                          style="flex: 1; margin-right: 8px;">
                                </el-input>
                                <el-button type="primary"
                                           icon="el-icon-search"
                                           v-on:click="openOrgSelectDialog">
                                    选择
                                </el-button>
                            </div>
                            <el-input v-model="form.sales_department_id" type="hidden"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第五行：销售负责人、状态（启用/停用） -->
                <el-row>
                    <el-col :span="12">
                        <!-- 销售负责人：动态下拉组件 -->
                        <el-form-item label="销售负责人" required class="form-item">
                            <el-select v-model="form.person_in_charge" placeholder="请选择" v-on:change="handlePersonChange">
                                <el-option v-for="item in personInChargeOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="状态" required class="form-item">
                            <el-radio v-model="form.status" label="1">启用</el-radio>
                            <el-radio v-model="form.status" label="0">停用</el-radio>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第六行：客户地址 -->
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="客户地址" class="form-item">
                            <el-input v-model="form.customers_address" placeholder="请输入客户地址"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第七行：备注 -->
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注" class="form-item">
                            <el-input v-model="form.note" type="textarea" placeholder="请输入备注" class="note-input"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <!-- 财务信息 -->
        <div class="form-group">
            <h3>财务信息</h3>
            <el-form ref="financeForm" :model="form" label-width="120px">
                <!-- 第一行：账户名称、纳税人识别号 -->
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="账户名称" class="form-item">
                            <el-input v-model="form.account_name" placeholder="请输入账户名称"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="纳税人识别号" class="form-item">
                            <el-input v-model="form.taxid" placeholder="请输入纳税人识别号"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第二行：银行账户、开户银行 -->
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="银行账户" class="form-item">
                            <el-input v-model="form.bank_account" placeholder="请输入银行账户"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="开户银行" class="form-item">
                            <el-input v-model="form.opening_bank" placeholder="请输入开户银行"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 第三行：开户行地址 -->
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="开户行地址" class="form-item">
                            <el-input v-model="form.bkaddr" placeholder="请输入开户行地址"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <!-- 上传附件 -->
        <div class="form-group">
            <h3>上传附件</h3>
            <div class="upload-area">
                <el-upload action="/CustomerManagement/UploadFile"
                           :file-list.sync="fileList"
                           :on-success="handleUploadSuccess"
                           :before-upload="beforeUpload"
                           :limit="3">
                    <el-button type="primary">上传</el-button>
                </el-upload>
                <div class="tip">您可以上传 doc、pdf、rar 等格式的文件，单个文件上传最大 200MB。</div>
            </div>
        </div>

        <!-- 树形选择弹窗 -->
        <el-dialog v-model="orgSelectDialogVisible"
                   title="选择销售部门"
                   width="450px"
                   style="z-index: 9999;">
            <div style="margin-bottom: 16px;">
                <el-input v-model="orgSearchKeyword"
                          placeholder="输入部门名称搜索"
                          clearable
                          v-on:keyup.enter="searchOrgTree">
                    <template #append>
                        <el-button type="primary"
                                   v-on:click="searchOrgTree"
                                   icon="Search"
                                   style="padding: 0 15px;">
                            搜索
                        </el-button>
                    </template>
                </el-input>
            </div>
            <el-tree :data="orgTree"
                     :props="{
                value: 'organizationId',
                label: 'organizationName',
                children: 'children'
            }"
                     v-on:node-click="handleOrgNodeClick"
                     node-key="organizationId"
                     :highlight-current="true"
                     default-expand-all>
            </el-tree>
            <template #footer>
                <div class="dialog-footer">
                    <el-button v-on:click="orgSelectDialogVisible = false">取消</el-button>
                    <el-button type="primary" v-on:click="confirmOrgSelect">确定</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 操作按钮 -->
        <div style="margin-top: 20px;">
            <el-button v-on:click="goBack">关闭</el-button>
            <el-button type="primary" v-on:click="submitUpdate">保存修改</el-button>
        </div>
    </div>

    <script>
        const { createApp, ref, onMounted } = Vue;
        const app = createApp({
            setup() {
                // 1. 表单核心数据
                const form = ref({
                    customer_code: '',       // 客户编码
                    customer_name: '',       // 客户名称
                    job_type: '',            // 所属行业ID（字符串类型，与下拉框匹配）
                    sources_of_customers: '',// 客户来源ID（字符串类型，与下拉框匹配）
                    contact_person: '',      // 联系人
                    contact_phone_number: '',// 联系电话
                    email_address: '',       // 电子邮箱
                    customers_address: '',   // 客户地址
                    sales_department_id: '',  // 销售部门ID
                    sales_dept_name: '',     // 销售部门名称
                    account_name: '',        // 账户名称
                    taxid: '',               // 纳税人识别号
                    bank_account: '',        // 银行账户
                    opening_bank: '',        // 开户银行
                    bkaddr: '',              // 开户行地址
                    note: '',                // 备注
                    person_in_charge: '',    // 销售负责人ID
                    status: '1',             // 状态：1=启用，0=停用
                    create_by: '',           // 创建人
                    create_time: '',         // 创建时间
                    update_by: 'admin',      // 更新人
                    update_time: '',         // 更新时间
                    annex_code: '',          // 附件编号
                });

                // 2. 下拉选单数据
                const industryOptions = ref([]);       // 所属行业选项
                const customersourceOptions = ref([]); // 客户来源选项
                const fileList = ref([]);              // 上传文件列表
                const personInChargeOptions = ref([]); // 销售负责人选项

                // 3. 部门树形选择相关变量
                const orgSelectDialogVisible = ref(false);
                const orgTree = ref([]);
                const selectedOrgId = ref(null);
                const orgSearchKeyword = ref('');
                const customerCode = ref(''); // 从URL获取的客户编号

                // 4. 获取后端字典数据
                const getIndustryDict = async () => {
                    try {
                        const response = await axios.get('/api/Dict/datas/Industry');
                        industryOptions.value = response.data || [];
                        console.log("所属行业字典数据:", industryOptions.value);
                    } catch (error) {
                        console.error('获取所属行业失败：', error);
                        ElementPlus.ElMessage.error('所属行业数据加载失败');
                    }
                };

                const getCustomerSourceDict = async () => {
                    try {
                        const response = await axios.get('/api/Dict/datas/CustomerSource');
                        customersourceOptions.value = response.data || [];
                        console.log("客户来源字典数据:", customersourceOptions.value);
                    } catch (error) {
                        console.error('获取客户来源失败：', error);
                        ElementPlus.ElMessage.error('客户来源数据加载失败');
                    }
                };

                // 5. 从URL参数中获取客户编号
                const getUrlParams = () => {
                    const params = new URLSearchParams(window.location.search);
                    customerCode.value = params.get('customerCode') || '';
                };

                // 6. 加载客户详情
                const loadCustomerDetail = async () => {
                    if (!customerCode.value) return;
                    try {
                        // 先获取字典数据
                        await getIndustryDict();
                        await getCustomerSourceDict();

                        // 获取客户详情数据
                        const response = await axios.get('/CustomerManagement/GetCustomerEdit', {
                            params: { customerCode: customerCode.value }
                        });
                        const data = response.data.data;

                        if (response.data.success) {
                            console.log("后端返回的原始数据:", data);

                            // 加载部门树用于回显部门名称
                            await loadOrgTree();

                            // 查找部门名称
                            const findDeptName = (tree, deptId) => {
                                for (const node of tree) {
                                    if (node.organizationId === deptId) {
                                        return node.organizationName;
                                    }
                                    if (node.children && node.children.length > 0) {
                                        const childName = findDeptName(node.children, deptId);
                                        if (childName) return childName;
                                    }
                                }
                                return '';
                            };

                            // 关键修改：将int类型的ID转换为字符串，确保与下拉框选项类型一致
                            form.value = {
                                ...data,
                                job_type: data.job_type.toString(),       // int转string
                                sources_of_customers: data.sources_of_customers.toString(), // int转string
                                status: data.status.toString(),
                                sales_department_id: data.sales_department_id || '',
                                sales_dept_name: findDeptName(orgTree.value, data.sales_department_id) || '',
                                person_in_charge: data.person_in_charge ? data.person_in_charge.toString() : ''
                            };

                            console.log("转换后的表单数据:", form.value);

                            // 加载附件
                            if (form.value.annex_code) {
                                await loadAttachments(form.value.annex_code);
                            }

                            // 加载对应部门的负责人列表
                            if (form.value.sales_department_id) {
                                await handleDeptChange(form.value.sales_department_id);
                            } else {
                                await loadAllPersonInCharge();
                            }
                        }
                    } catch (error) {
                        console.error('加载客户详情失败：', error);
                        ElementPlus.ElMessage.error('加载客户信息失败');
                    }
                };

                // 7. 部门树形选择相关方法
                const loadOrgTree = async () => {
                    try {
                        const response = await axios.get('/SalesOrder/GetOrganizationTree');
                        orgTree.value = response.data;
                    } catch (error) {
                        console.error('加载部门树失败：', error);
                        ElementPlus.ElMessage.error('加载部门树失败');
                    }
                };

                const openOrgSelectDialog = async () => {
                    await loadOrgTree();
                    orgSelectDialogVisible.value = true;
                };

                const handleOrgNodeClick = (node) => {
                    selectedOrgId.value = node.organizationId;
                };

                const confirmOrgSelect = async () => {
                    if (!selectedOrgId.value) {
                        ElementPlus.ElMessage.warning('请选择部门');
                        return;
                    }
                    const findNode = (tree, id) => {
                        for (const node of tree) {
                            if (node.organizationId === id) return node;
                            if (node.children && node.children.length > 0) {
                                const childNode = findNode(node.children, id);
                                if (childNode) return childNode;
                            }
                        }
                        return null;
                    };
                    const selectedNode = findNode(orgTree.value, selectedOrgId.value);
                    if (selectedNode) {
                        form.value.sales_department_id = selectedNode.organizationId;
                        form.value.sales_dept_name = selectedNode.organizationName;
                        await handleDeptChange(selectedNode.organizationId);
                        orgSelectDialogVisible.value = false;
                    }
                };

                const searchOrgTree = async () => {
                    try {
                        if (!orgSearchKeyword.value) {
                            await loadOrgTree();
                        } else {
                            const response = await axios.get('/SalesOrder/GetOrganizationTree2', {
                                params: { keyword: orgSearchKeyword.value }
                            });
                            orgTree.value = response.data;
                        }
                    } catch (error) {
                        console.error('搜索部门树失败：', error);
                        ElementPlus.ElMessage.error('搜索部门树失败');
                    }
                };

                // 8. 销售负责人相关方法
                const loadAllPersonInCharge = async () => {
                    try {
                        const res = await axios.get('/SalesOrder/GetAllPersonInCharge');
                        personInChargeOptions.value = res.data.map(item => ({
                            value: item.userId.toString(), // 确保是字符串类型
                            label: item.userName
                        }));
                    } catch (err) {
                        ElementPlus.ElMessage.error('加载负责人列表失败');
                    }
                };

                const handleDeptChange = async (deptId) => {
                    try {
                        const res = await axios.get('/SalesOrder/GetUserByDeptId', { params: { deptId } });
                        personInChargeOptions.value = res.data.map(item => ({
                            value: item.userId.toString(), // 确保是字符串类型
                            label: item.userName
                        }));
                        // 如果当前负责人不在新的部门列表中，则清空
                        if (form.value.person_in_charge &&
                            !personInChargeOptions.value.some(item => item.value === form.value.person_in_charge)) {
                            form.value.person_in_charge = '';
                        }
                    } catch (err) {
                        ElementPlus.ElMessage.error('加载负责人失败');
                    }
                };

                const handlePersonChange = async (userId) => {
                    if (!userId) {
                        form.value.sales_department_id = '';
                        form.value.sales_dept_name = '';
                        return;
                    }
                    try {
                        const res = await axios.get('/SalesOrder/GetDeptByUserId', { params: { userId } });
                        if (res.data) {
                            form.value.sales_department_id = res.data.organizationId;
                            form.value.sales_dept_name = res.data.organizationName;
                        } else {
                            ElementPlus.ElMessage.warning('该用户无所属部门');
                            form.value.person_in_charge = '';
                        }
                    } catch (err) {
                        ElementPlus.ElMessage.error('获取部门失败');
                    }
                };

                // 9. 附件相关方法
                const beforeUpload = (file) => {
                    const allowedTypes = ['application/msword', 'application/pdf', 'application/x-rar-compressed'];
                    const maxSize = 200 * 1024 * 1024;
                    if (!allowedTypes.includes(file.type)) {
                        ElementPlus.ElMessage.error('仅支持 doc、pdf、rar 格式文件');
                        return false;
                    }
                    if (file.size > maxSize) {
                        ElementPlus.ElMessage.error('单个文件最大不能超过200MB');
                        return false;
                    }
                    return true;
                };

                const handleUploadSuccess = (response) => {
                    if (response.success) {
                        form.value.annex_code = response.data.annex_code;
                        ElementPlus.ElMessage.success('附件上传成功');
                    } else {
                        ElementPlus.ElMessage.error('附件上传失败：' + response.message);
                    }
                };

                const loadAttachments = async (annexCode) => {
                    try {
                        const res = await axios.get(`/api/Supplier/GetAttachments?annexCode=${annexCode}`);
                        if (res.data.success) {
                            fileList.value = res.data.data.map(file => ({
                                name: file.fileName,
                                url: file.fileUrl,
                                uid: file.id
                            }));
                        } else {
                            ElementPlus.ElMessage.error(res.data.message);
                        }
                    } catch (error) {
                        console.error('加载附件失败：', error);
                        ElementPlus.ElMessage.error('加载附件失败，请重试');
                    }
                };

                // 10. 提交修改
                const submitUpdate = async () => {
                    try {
                        // 前端简单验证
                        if (!form.value.customer_name) {
                            ElementPlus.ElMessage.warning('请输入客户名称');
                            return;
                        }
                        if (!form.value.job_type) {
                            ElementPlus.ElMessage.warning('请选择所属行业');
                            return;
                        }
                        if (!form.value.sources_of_customers) {
                            ElementPlus.ElMessage.warning('请选择客户来源');
                            return;
                        }
                        if (!form.value.sales_department_id) {
                            ElementPlus.ElMessage.warning('请选择销售部门');
                            return;
                        }
                        if (!form.value.person_in_charge) {
                            ElementPlus.ElMessage.warning('请选择销售负责人');
                            return;
                        }

                        const submitData = {
                            customer_code: form.value.customer_code,
                            customer_name: form.value.customer_name,
                            job_type: parseInt(form.value.job_type), // string转int
                            sources_of_customers: parseInt(form.value.sources_of_customers), // string转int
                            contact_person: form.value.contact_person,
                            contact_phone_number: form.value.contact_phone_number,
                            email_address: form.value.email_address,
                            customers_address: form.value.customers_address,
                            sales_department_id: form.value.sales_department_id ? Number(form.value.sales_department_id) : '',
                            account_name: form.value.account_name,
                            taxid: form.value.taxid,
                            bank_account: form.value.bank_account,
                            opening_bank: form.value.opening_bank,
                            bkaddr: form.value.bkaddr,
                            note: form.value.note,
                            person_in_charge: form.value.person_in_charge ? parseInt(form.value.person_in_charge) : '',
                            status: form.value.status.toString(),
                            update_by: form.value.update_by,
                            update_time: new Date().toISOString(),
                            annex_code: form.value.annex_code
                        };

                        console.log("提交到后端的参数：", submitData);

                        const res = await axios.put('/CustomerManagement/UpdateCustomer', submitData);
                        if (res.data.success) {
                            ElementPlus.ElMessage.success('修改成功');
                            setTimeout(() => window.history.back(), 1000);
                        } else {
                            ElementPlus.ElMessage.error(res.data.Message || '修改失败');
                        }
                    } catch (err) {
                        console.error('提交修改失败:', err);
                        ElementPlus.ElMessage.error(err.response?.data?.Message || '服务器异常');
                    }
                };

                // 11. 按钮事件
                const goBack = () => window.history.back();

                // 12. 页面挂载时加载数据
                onMounted(() => {
                    getUrlParams();
                    loadCustomerDetail();
                });

                return {
                    form,
                    industryOptions,
                    customersourceOptions,
                    fileList,
                    personInChargeOptions,
                    orgSelectDialogVisible,
                    orgTree,
                    selectedOrgId,
                    orgSearchKeyword,
                    goBack,
                    handleUploadSuccess,
                    beforeUpload,
                    submitUpdate,
                    openOrgSelectDialog,
                    handleOrgNodeClick,
                    confirmOrgSelect,
                    searchOrgTree,
                    handleDeptChange,
                    handlePersonChange
                };
            }
        });
        app.use(ElementPlus);
        app.mount('.container');
    </script>
</body>

</html>